package com.eoner.baselibrary.utils;

import android.util.Base64;

import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class EncryptUtil {

    //RSA加密
    public static String encryptRSA(String sSrc, String sKey) {
        try {
            Key key = getPublicKey(sKey);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] b = sSrc.getBytes();
            byte[] b1 = cipher.doFinal(b);
            return new String(Base64.encode(b1,Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //RSA解密
    public static String decryptionRSA(String sSrc, String sKey) {
        try {
            Key key = getPublicKey(sKey);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] b = Base64.decode(sSrc,Base64.DEFAULT);
            byte[] b1 = cipher.doFinal(b);
            return new String(b1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 得到公钥
     *
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                Base64.decode(key.getBytes(),Base64.DEFAULT));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

}